package com.mvc.controller;

import com.common.Constant;
import com.soecode.wxtools.api.IService;
import com.soecode.wxtools.api.WxConfig;
import com.soecode.wxtools.api.WxConsts;
import com.soecode.wxtools.api.WxMessageRouter;
import com.soecode.wxtools.bean.*;
import com.soecode.wxtools.bean.result.SenderResult;
import com.soecode.wxtools.bean.result.TemplateSenderResult;
import com.soecode.wxtools.bean.result.WxUserListResult;
import com.soecode.wxtools.exception.WxErrorException;
import com.soecode.wxtools.util.xml.XStreamTransformer;
import com.stock.StockMsg;
import com.wxmsg.AdminHandle;
import com.wxmsg.DefaultHandle;
import com.wxmsg.EventHandle;
import com.wxmsg.UserHandle;
import net.sf.json.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by lzb on 2018/5/11.
 */
@RestController
@RequestMapping("/wx")
public class WxCtr {
    //实例化 统一业务API入口
    private IService iService = Constant.iService;

    @Resource(name = "redisTemplate")
    private RedisTemplate redisTemplate;

    @GetMapping("/msg")
    @ResponseBody
    public String test(String signature,String timestamp,String nonce,String echostr ) {
        if (iService.checkSignature(signature, timestamp, nonce, echostr)) {
            return echostr;
        }

        return null;
    }

    @PostMapping("/msg")
    @ResponseBody
    public String handleMsg(String signature,String timestamp,String nonce,String echostr ,@RequestParam(required = false) String encrypt_type,String msg_signature,HttpServletRequest request) throws Exception {
        WxMessageRouter router = new WxMessageRouter(iService);
        WxXmlMessage wx = null;
        wx=(encrypt_type != null && "aes".equals(encrypt_type))?WxXmlMessage.decryptMsg(request.getInputStream(), WxConfig.getInstance(), timestamp,nonce, msg_signature):XStreamTransformer.fromXml(WxXmlMessage.class, request.getInputStream());
        System.out.println(wx.toString());
        router.rule().msgType("event").handler(new EventHandle()).end();
        router.rule().fromUser("oqcqkw8qmuLdS9qzm6p7oVhrIKPc").rContent("^cmd (.)+").handler(new AdminHandle()).end();
        router.rule().rContent("^cmd (.)+").handler(new UserHandle()).end();
        router.rule().handler(new DefaultHandle()).end();
        // 把消息传递给路由器进行处理
        WxXmlOutMessage xmlOutMsg = router.route(wx);
        if(xmlOutMsg==null)return null;



        return (encrypt_type != null && "aes".equals(encrypt_type))?WxXmlOutMessage.encryptMsg(WxConfig.getInstance(), xmlOutMsg.toXml(), timestamp, nonce):xmlOutMsg.toXml();
    }

    @RequestMapping("/sendmsg")
    @ResponseBody
    public String sendmsg() throws Exception {
        WxOpenidSender sender = new WxOpenidSender();
        sender.setTouser(Arrays.asList("oqcqkw8qmuLdS9qzm6p7oVhrIKPc","oqcqkw2WuZIsEHKjqwX80ck-VFrw"));
        sender.setMsgtype("text");
        sender.setText(new SenderContent.Text("价格变动通知"));
        System.out.println(sender.toJson());
        SenderResult result = iService.sendAllByOpenid(sender);
        return result.toString();
    }

    @RequestMapping("/sublist")
    @ResponseBody
    public String sublist() throws Exception {
        String nextid="";
        WxUserListResult result = null;
        result = iService.batchGetUserOpenId(nextid);
        System.out.println(result.getData());
        return null;
    }

    @RequestMapping("/addmenu")
    @ResponseBody
    public String addmenu() throws Exception {
        WxMenu menu = this.iService.getMenu().getMenu();
        List<WxMenu.WxMenuButton> btnList = new ArrayList<>();
//设置CLICK类型的按钮1

        WxMenu.WxMenuButton btn2 = new WxMenu.WxMenuButton();
        btn2.setType(WxConsts.BUTTON_CLICK);
        btn2.setKey("nowPrice");
        btn2.setName("涡轮套利");

        WxMenu.WxMenuButton btn1 = new WxMenu.WxMenuButton();
        btn1.setType(WxConsts.BUTTON_CLICK);
        btn1.setKey("MDGE");
        btn1.setName("美的&格力");


        btnList.add(btn2);
        btnList.add(btn1);
        menu.setButton(btnList);
        String rs=this.iService.createMenu(menu, false);
        System.out.println(rs);
        System.out.println(this.iService.getMenu().toJson());


        return null;
    }

    @RequestMapping("/sendMsg")
    @ResponseBody
    public String sendMsg() throws Exception {

        TemplateSender sender= StockMsg.checkWl(
                Arrays.asList(
                        (String[]) redisTemplate.opsForSet().members("oqcqkw8qmuLdS9qzm6p7oVhrIKPc").toArray(new  String[]{})
                ),
                Arrays.asList((String[]) redisTemplate.opsForSet().members("oqcqkw8qmuLdS9qzm6p7oVhrIKPc"+"_BUY").toArray(new  String[]{}))
        );
        if(sender!=null)Constant.iService.templateSend(sender);

//        JSONObject json=new JSONObject();
//        json.put("","")

//        TemplateSender sender = new TemplateSender();
//        sender.setTouser("oqcqkw8qmuLdS9qzm6p7oVhrIKPc");
//        sender.setTemplate_id("TW2oT9lA27AdsSSvrvplqqbIm7ECL_m_sDS-iSUd888");
//        KeyWord keyWord1=new KeyWord("11111");
////        keyWord1.value="11111";
//
//        sender.getData().put("first",keyWord1);
////        sender.setUrl("#");
//        try {
//
//            System.out.println(sender.toJson());
//            TemplateSenderResult result = iService.templateSend(sender);
////            System.out.println(result.toString());
//            return result.toString();
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//        }
        return null;
    }


}
